package net.java.mediasystems.web.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;

import net.java.mediasystems.database.core.model.Genre;
import net.java.mediasystems.database.core.service.GenreService;

public class GenreConverter implements Converter {

	private List<Genre> genreList;
	
	private GenreService genreService;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (!StringUtils.isEmpty(value)) {
			for (Genre curGenre : this.genreList) {
				if (curGenre.getId().longValue() ==  Long.parseLong(value)) {
					return curGenre;
				}
			}
		}
		return null;
	}
	
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		Genre genre = (Genre) value;
		return genre.getId().toString();
	}
	
	/**
	 * Special Set()-Method: The GenreList will be initialized immediately after setting the GenreService.
	 * 
	 * @param genreService GenreService
	 */
	public void setGenreService(GenreService genreService) {
		this.genreService = genreService;
		this.genreList = this.genreService.getAllGenres();
	}
	
	/**
	 * Add a new Genre to the Genres-List.
	 * 
	 * @param genre Genre
	 */
	public void addNewGenreItem(Genre genre) {
		this.genreList.add(genre);
	}
}
